package naga.x.platform2.app.support;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import naga.x.platform2.app.AppException;
import naga.x.platform2.app.Channel;
import naga.x.platform2.app.mapper.CodeMapper;
import naga.x.platform2.app.model.Code;

@Service
public class CodeSupport {

	@Autowired
	private CodeMapper mapper;
	
	public static final int CODE_BAD_REQUEST = -1; // 非法请求
	public static final int CODE_NOT_FOUND = -2; // 礼包码错误
	public static final int CODE_RECEIVED = -3; // 礼包已被领取
	public static final int CODE_NO_PERMISSION = -4; // 没有权限领取（eg.渠道限制）
	
	public Code receive(String code, long playerId, Channel channel) throws AppException {
		Code c = mapper.find(code);
		if (c == null) {
			throw new AppException(CODE_NOT_FOUND);
		}
		if (c.getChannel() != null && c.getChannel() != channel) {
			throw new AppException(CODE_NO_PERMISSION);
		}
		int received = mapper.countBy(c.getType(), playerId);
		if (received >= c.getLimit()) {
			// 已领取过该类型的礼包
			throw new AppException(CODE_RECEIVED);
		}
		c.setState(Code.State.RECEIVED);
		c.setReceiver(playerId);
		int n = mapper.update(c);
		if (n <= 0) {
			throw new AppException(CODE_RECEIVED);
		}
		return c;
	}
	
}
